#include"../log/log.h"
#include<chrono>
void bench(const std::string name,size_t thr_count,size_t msg_count,size_t msg_len)
{
    logs::Logger::ptr logger = logs::getlogger(name);
    if(logger.get() == nullptr)
        return;
    //2 组织一条日志留了一个空位给\n，也就是说一条日志只放msg_len-1个有效字符,留一个放\n,因为\n也是一个字符
    std::string msg(msg_len-1,'A');
    std::cout<<"测试日志: "<<msg_count<<"条"<<" 总大小"<<msg_count*msg_len<<std::endl;
    //3 创建线程
    std::vector<std::thread> vt;
    std::vector<double> vi;//记录每个线程耗时
    size_t msg_per_count = msg_count / thr_count;
    for(int i = 0; i < thr_count;i++)
    {
        vt.emplace_back([&,i]()
        {
            //计时开始
            auto begin = std::chrono::high_resolution_clock::now();
            for(int j = 0 ; j < msg_per_count;j++)//写入日志
                logger->Fatal("%s",msg.c_str());
            auto end = std::chrono::high_resolution_clock::now();
            std::chrono::duration<double> cost = end - begin;
            //计时结束

            vi.push_back(cost.count());
            std::cout<<"线程: "<<i<<"输出数量 "<<msg_per_count <<" 耗时: "<<cost.count()<<"s"<<std::endl;
        });
    }    
    //必须先回收线程,不然主线程先退出,还会报段错误
    for(auto& e : vt)
    {
        e.join();
    }
    //计算总耗时
    double max_cost = vi[0];
    for(int i = 1; i < vi.size();i++)
    {
        if(vi[i] > max_cost)
        {
            max_cost = vi[i];
        }
    }
    size_t size_per_sec = (msg_count *  msg_len)/(max_cost*1024);//每秒输出日志大小,单位k
    size_t msg_per_sec = msg_count/max_cost;//每秒输出日志条数
    std::cout<<"总耗时: "<<max_cost<<"s"<<std::endl;
    std::cout<<"每秒输出日志大小 "<<size_per_sec<<"k"<<std::endl;
    std::cout<<"每秒输出日志条数 "<<size_per_sec<<"条"<<std::endl;
}
void syncbench()
{
    // bench("sync",1,1000000,100);//同步单线程检测
    bench("sync",15,1000000,100);//同步多线程检测
}
void Asyncbench()
{
    // bench("Async",1,1000000,100);//异步单线程检测
    bench("Async",14,1000000,100);//异步单线程检测
}

int main()
{
    std::shared_ptr<logs::Globalloggerbuild> localbuild(new(logs::Globalloggerbuild));//创建一个全局建造者
    //建造日志器对象成员
    localbuild->buildlevel(logs::loglevel::level::DEBUG);
    localbuild->buildformater("%d{%H:%M:%S}[%f:%l][%m]%n");
    localbuild->buildlogname("Async");
    localbuild->buildUnsafeAsync();
    localbuild->buildloggertype(logs::LoggerType::Asynclooper);
    localbuild->buildsink<logs::Filesink>("./logs/test2.log");
    //组装后返回日志器,全局建造者返回的是全局日志器
    localbuild->build();
    Asyncbench();
    return 0;
}